package njust.csc.aecore.utils

import com.google.gson.stream.MalformedJsonException
import io.github.oshai.kotlinlogging.KotlinLogging
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.nio.charset.StandardCharsets
private val logger = KotlinLogging.logger {}

/**
 * @Author ZhouHang
 * @Date 24/7/4 周四
 */
object NetworkUtils {
    private const val BASEURL = "https://api.zhizengzeng.com/v1/chat/completions"
    private const val APIKEY = "sk-zk234b4c75ee2fcb76b48fa011b07791dbf6655976e531c3"
    private val url = URL(BASEURL)

    /**
     * 向大模型接口发送请求
     * @param body 请求体序列化后的 json 字符串
     * */
    fun post(body: String): String {
        val connection = url.openConnection() as HttpURLConnection
        connection.setRequestMethod("POST")
        connection.setRequestProperty("Content-Type", "application/json")
        connection.setRequestProperty("Authorization", "Bearer $APIKEY")
        connection.setDoOutput(true)

        DataOutputStream(connection.outputStream).use { wr ->
            wr.write(body.toByteArray(StandardCharsets.UTF_8))
            wr.flush()
        }
        val response = StringBuilder()
        BufferedReader(
            InputStreamReader(connection.inputStream)
        ).use { `in` ->
            var inputLine: String?
            while ((`in`.readLine().also { inputLine = it }) != null) {
                response.append(inputLine)
            }
        }
        logger.info { response }

        var ret = ""
        try {
            val resultMap = SerializeUtils.toMap(response.toString())
            val choices = resultMap["choices"] as List<*>
            val tmp = choices[0] as Map<*, *>
            val message = tmp["message"] as Map<*, *>
            ret = message["content"] as String
        } catch (e: NullPointerException) {
            logger.info { "模型调用发生错误" }
            ret = ""
        } catch (e: MalformedJsonException) {
            logger.info { "模型调用发生错误" }
            ret = ""
        } finally {
            connection.disconnect()
        }
        return ret
    }
}
